package com.javabasic.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiongmin
 * @version 0.0.1
 * @description Created by work on 2021/11/3 9:58 下午
 * @see [1624. Largest Substring Between Two Equal Characters](https://leetcode-cn.com/problems/largest-substring-between-two-equal-characters/)
 */
public class LargestSubstringBetweenTwoEqualCharacters {

    /**
     * 解法一：利用Map暴力解法
     * @param s
     * @return
     */
    public int maxLengthBetweenEqualCharacters(String s) {
        Map<Integer, Integer> charToIndex = new HashMap<>();
        int len = s.length();
        int result = -1, index, key;
        for (int i = 0; i < len; i++) {
            key = s.charAt(i) - 'a';
            index = charToIndex.getOrDefault(key, i);
            if (index != i && (i - index - 1) > result) {
                result = i - index - 1;
            }
            if (index == i) {
                charToIndex.put(key, i);
            }
        }
        return result;
    }
}
